package com.exercise.AndroidCamera;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Locale;

import javax.security.auth.PrivateCredentialPermission;

import com.exercise.AndroidCamera.LoginActivity.UserLoginTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/*
기능 : 회원등록
작성 : 하드캔
완료일 : 2014.09.26 
	*/
public class RegisterActivity extends BaseActivity {
	
	public static final String EXTRA_TEXT = "com.example.android.authenticatordemo.extra.TEXT";
			
	private EditText editID;
	private EditText editPassword;
	private EditText editRe_Password;
	private EditText editName;
	private EditText editPhone;
	private EditText editEmail;
	private int flag=0;
	private String strCheckID;
	private String strRegisterSuccess;
	private String checkedID;
	private boolean cancel;
	
	private String id;
	private String pw;
	private String rePw;
	private String name;
	private String phone;
	private String email;
	
	private RegisterAsyncTask registerAsyn;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		
		id = getIntent().getStringExtra(EXTRA_TEXT);
		editID = (EditText) findViewById(R.id.editID);
		editID.setText(id);
		
		pw = getIntent().getStringExtra(EXTRA_TEXT);
		editPassword = (EditText) findViewById(R.id.editPW);
		editPassword.setText(pw);
		
		rePw = getIntent().getStringExtra(EXTRA_TEXT);
		editRe_Password = (EditText) findViewById(R.id.editRePW);
		editRe_Password.setText(rePw);
		
		name = getIntent().getStringExtra(EXTRA_TEXT);
		editName = (EditText) findViewById(R.id.editName);
		editName.setText(name);
		
		phone = getIntent().getStringExtra(EXTRA_TEXT);
		editPhone = (EditText) findViewById(R.id.editPhone);
		editPhone.setText(phone);
		
		email = getIntent().getStringExtra(EXTRA_TEXT);
		editEmail = (EditText) findViewById(R.id.editEmail);
		editEmail.setText(email);
		
		findViewById(R.id.btnCheck).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						checkIDAsyncTask checkID = new checkIDAsyncTask();
						checkID.execute();
					}
				});
		
		findViewById(R.id.btnOK).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						if(flag==1){
							if(editID.getText().toString().equals(checkedID) && !editID.getText().toString().isEmpty()){
								attemptRegister();
								if(!cancel)
									finish();
							}
						}
						else{
							new AlertDialog.Builder(RegisterActivity.this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("알림").setMessage("아이디 중복체크를 하세요.")
					    	.setPositiveButton("확인", null).show();
							flag=0;
						}
					}
				});
		
		getActionBar().setTitle("Post Memories");
		getActionBar().setDisplayShowHomeEnabled(false);
		getActionBar().setDisplayHomeAsUpEnabled(true);
	}
	

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	     
	    switch(item.getItemId()){

	    case android.R.id.home:
	    	onBackPressed();
	    	break;

	    default:
	        return false;
	    }
	    return true;
	}

	
	public void attemptRegister() {
		if (registerAsyn != null) {
			return;
		}
		
		// Reset errors.
		editID.setError(null);
		editPassword.setError(null);
		editRe_Password.setError(null);
		editName.setError(null);
		editPhone.setError(null);
		editEmail.setError(null);

		// Store values at the time of the register attempt.
		id = editID.getText().toString();
		pw = editPassword.getText().toString();
		rePw = editRe_Password.getText().toString();
		name = editName.getText().toString();
		phone = editPhone.getText().toString();
		email = editEmail.getText().toString();

		cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(pw) || pw.length() < 4) {
			editPassword.setError(getString(R.string.error_field_required));
			editPassword.requestFocus();
			cancel = true;
		} 

		if (!rePw.equals(pw)){
			editRe_Password.setError(getString(R.string.error_not_equal));
			editRe_Password.requestFocus();
			cancel = true;
		}
		
		// Check for a valid name.
		if (TextUtils.isEmpty(name)) {
			editName.setError(getString(R.string.error_field_required));
			editName.requestFocus();
			cancel = true;
		} 
		
		// Check for a valid phone.
		try{
			if (TextUtils.isEmpty(phone)) {
				editPhone.setError(getString(R.string.error_field_required));
				editPhone.requestFocus();
				cancel = true;
			}
		} catch (NumberFormatException nfe) {
			editPhone.setError(getString(R.string.error_not_number));
			editPhone.requestFocus();
			cancel = true;
	    // Not a number.
		}
		
		// Check for a valid Email.
		if (TextUtils.isEmpty(email)) {
			editEmail.setError(getString(R.string.error_field_required));
			editEmail.requestFocus();
			cancel = true;
		} 
		else if (!email.contains("@")) {
			editEmail.setError(getString(R.string.error_invalid_email));
			editEmail.requestFocus();
			cancel = true;
		}

		if (!cancel) {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			registerAsyn = new RegisterAsyncTask();
			registerAsyn.execute();
		}
	}
	
	public class RegisterAsyncTask extends AsyncTask<String, String, String>{
		
		public RegisterAsyncTask() {
			// TODO Auto-generated constructor stub
		}
		
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
            
        	register(RegisterActivity.this);

			return null;
		}
		@Override
    	protected void onPostExecute(String result) {
    		// TODO Auto-generated method stub
    		super.onPostExecute(result);
    		
    		if(strRegisterSuccess.equals("success")){
        		
        		Toast.makeText(RegisterActivity.this, "가입에 성공하였습니다!", Toast.LENGTH_SHORT).show();

        		finish();
        		
        	}else if(strRegisterSuccess.equals("fail")){
        		try {
					throw new Exception(strRegisterSuccess);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        	}else{
        		try {
					throw new Exception(strRegisterSuccess);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        	}
    		
    		onCancelled();
		}
    }
		
		protected String[] register(Context context){
			String pString = null;
			HttpURLConnection conn = null;
			BufferedReader br = null;
			
			String[] result = new String[2];
			result[0] = "error"; //JSON flag
			result[1] = null; //message
			
			try{
	        	StringBuilder builder = new StringBuilder();
	        	
	        	URL url = new URL("http://54.199.194.197/register.php");
	        	conn = (HttpURLConnection)url.openConnection();
	        	
	        	if(conn != null){
	        		conn.setConnectTimeout(15000);	
	        		conn.setReadTimeout(15000);
	        		conn.setDefaultUseCaches(false);
	            	conn.setDoInput(true); 
	            	conn.setDoOutput(true); 
	            	conn.setRequestMethod("POST"); 
	            	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded"); 
	            	
	            	StringBuffer buffer = new StringBuffer();
	                buffer.append("user_id").append("=").append(id).append("&");                 
	                buffer.append("password").append("=").append(pw).append("&");
	                buffer.append("name").append("=").append(name).append("&");
	                buffer.append("phone").append("=").append(phone).append("&");
	                buffer.append("email").append("=").append(email);
	                
	                
	                OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
	                PrintWriter writer = new PrintWriter(outStream);
	                writer.write(buffer.toString());
	                writer.flush();
	                
	                
	                InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
	                br = new BufferedReader(inputStream);
	               
	            	String line;
	            	while((line = br.readLine()) != null){
	            	   builder.append(line);
	            	}
	               
	            	br.close();
	            	
	            	
	            	pString =  builder.toString();
	            	strRegisterSuccess = pString;
	            	Log.d("success???", strRegisterSuccess);
	            	
	            
	            	
	        	}else{
	        		
	        		throw new Exception("network error");
	        	}
	        	
	        }catch(SocketTimeoutException se){
	        	
	        	result[1] = "network error";
	        	
	        }catch(Exception e){
	        	
	        	result[1] = e.getMessage();
	        	
	        }finally{
	        	
	        	if(conn != null)
	        		conn.disconnect();

	        	if(br != null){
	        		try {
	        			br.close();
					} catch (Exception e2) {
						// TODO: handle exception
						result[1] = e2.getMessage();
					}
	        	}
	        }
	      
	        return result;
		}
	
	protected String[] check_id(Context context){
			String pString = null;
			HttpURLConnection conn = null;
			BufferedReader br = null;
			
			String[] result = new String[2];
			result[0] = "error"; //JSON flag
			result[1] = null; //message
			checkedID = editID.getText().toString();
			
			try{
	       	StringBuilder builder = new StringBuilder();
	       	
	       	URL url = new URL("http://54.199.194.197/boolean_register.php");
	       	conn = (HttpURLConnection)url.openConnection();
	       	
	       	if(conn != null){
	       		conn.setConnectTimeout(15000);	
	       		conn.setReadTimeout(15000);
	       		conn.setDefaultUseCaches(false); 
	           	conn.setDoInput(true); 
	           	conn.setDoOutput(true); 
	           	conn.setRequestMethod("POST"); 
	           	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
	           	StringBuffer buffer = new StringBuffer();
	           	
	            buffer.append("user_id").append("=").append(checkedID);
	            
	               
	               OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
	               PrintWriter writer = new PrintWriter(outStream);
	               writer.write(buffer.toString());
	               writer.flush();
	               
	               
	               InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
	               br = new BufferedReader(inputStream);
	              
	           	String line;
	           	while((line = br.readLine()) != null){
	           	   builder.append(line);
	           	}
	              
	           	br.close();
	           	
	           	pString =  builder.toString();
	           	strCheckID = pString;
	           	
	       	}else{
	       		
	       		throw new Exception("network error");
	       	}
	       	
	       }catch(SocketTimeoutException se){
	       	
	       	result[1] = "network error";
	       	
	       }catch(Exception e){
	       	
	       	result[1] = e.getMessage();
	       	
	       }finally{
	       	
	       	if(conn != null)
	       		conn.disconnect();

	       	if(br != null){
	       		try {
	       			br.close();
					} catch (Exception e2) {
						// TODO: handle exception
						result[1] = e2.getMessage();
					}
	       	}
	       }
	     
	       return result;
	}
   
   public class checkIDAsyncTask extends AsyncTask<String, String, String> {
	 @Override
	protected void onPreExecute() {
		super.onPreExecute();
	}
	   @Override
	protected String doInBackground(String... params) {
		check_id(RegisterActivity.this);
		
		return null;
	}
	   @Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);

		if(strCheckID.equals("false")){
			new AlertDialog.Builder(RegisterActivity.this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("중복체크").setMessage("있는 아이디입니다. 사용하실 수 없습니다.")
	    	.setPositiveButton("확인", null).show(); 
			flag=0;
		}
		else if(strCheckID.equals("true")){
			new AlertDialog.Builder(RegisterActivity.this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("중복체크").setMessage("없는 아이디입니다. 사용하실 수 있습니다.")
	    	.setPositiveButton("확인", null).show();
			flag=1;
		}
	}
	   @Override
	protected void onCancelled() {
		super.onCancelled();
	}
   }
}
